package com.bringway.framework.util.ftp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import org.apache.commons.lang.StringUtils;

import com.bringway.framework.exception.ServiceException;
import com.bringway.framework.util.DateUtils;
import com.bringway.framework.util.FileUtils;

public class FtpUtil {
	private static FtpConfig ftpConfig = null;

	/**
	 * 取得FTP服务器信息,包括Ip,Port,root,username,password等等。
	 * 
	 * @throws ServiceException
	 * @throws IOException
	 */
	public static FtpConfig getFtpConfig() throws ServiceException {
		if (ftpConfig != null) {
			ftpConfig.load();
			return ftpConfig;
		}
		ftpConfig = new FtpConfig();
		ftpConfig.load();
		if (StringUtils.isEmpty(ftpConfig.getHost()))
			throw new RuntimeException(
					"host must be empty! please check the applicationInfo");
		if (ftpConfig.getPort() <= 0)
			ftpConfig.setPort(21);
		if (StringUtils.isEmpty(ftpConfig.getRoot()))
			ftpConfig.setRoot("");
		if (ftpConfig.getRoot().length() > 0
				&& !ftpConfig.getRoot().startsWith("/"))
			ftpConfig.setRoot("/" + ftpConfig.getRoot());
		if (ftpConfig.getRoot().endsWith("/"))
			ftpConfig.setRoot(ftpConfig.getRoot().substring(0,
					ftpConfig.getRoot().length()));
		if (ftpConfig.getUsername() == null)
			ftpConfig.setUsername("");
		if (ftpConfig.getPassword() == null)
			ftpConfig.setPassword("");
		return ftpConfig;
	}

	/**
	 * 附件在FTP上的存储路径+名称
	 * 
	 * @param path1
	 *        路径1
	 * @param path2
	 *        路径2
	 * @param filename
	 *        文件名
	 * @throws ServiceException
	 */
	public static String getAttachFilePath(String path, String filename)
			throws ServiceException {
		StringBuffer sb = new StringBuffer();
		// 文件名
		sb.append(getAttachPath(path)).append(filename);
		return sb.toString();
	}

	/**
	 * 获取目录
	 * 
	 * @param path1
	 * @param path2
	 * @return
	 * @throws ServiceException
	 */
	private static String getAttachPath(String path)
			throws ServiceException {
		StringBuffer sb = new StringBuffer();
		// 路径
		sb.append(getFtpConfig().getRoot());
		if (sb.charAt(sb.length()-1)=='/'){
			sb.deleteCharAt(sb.length()-1);
		}
		sb.append('/').append(path);
		if (sb.charAt(sb.length()-1)=='/'){
			sb.deleteCharAt(sb.length()-1);
		}
		sb.append("/").append(DateUtils.toString(new Date(), "yyyy-MM"));
		// 文件名
		sb.append('/');
		return sb.toString();
	}

	/**
	 * 上传文件
	 * 
	 * @param orgCode
	 *        单位编码
	 * @param file
	 * @return String 存储在FTP上的完整路径名称
	 */
	public static String upload(String orgCode,InputStream is) {
		Ftp ftp = null;
		try {
			FtpConfig config = getFtpConfig();
			ftp = new Ftp(config.getHost(), config.getPort(), config
					.getUsername(), config.getPassword());
			ftp.login();
		} catch (Exception e) {
			if (ftp != null)
				ftp.logout();
		}

		String path = orgCode;
		String fileName = String.valueOf(System.currentTimeMillis());
		String remote = ftp.normalizeRemotePath(getAttachFilePath(path, fileName));
		OutputStream os = null;

		try {
			
			ftp.buildPath(remote.substring(0, remote.lastIndexOf("/")));
			ftp.logout();
			ftp.login();
			os = ftp.getOutputStream(remote);
			FileUtils.copyStream(is, os);
			return remote;
		} catch (Exception e) {

		} finally {
			if (os != null) {
				FileUtils.closeStream(os);
			}
		}
		return null;
	}

	/**
	 * 下载文件
	 * 
	 * @param path
	 * @param out
	 * @return boolean
	 */
	public static boolean download(String path, OutputStream out) {
		Ftp ftp = null;
		try {
			FtpConfig config = getFtpConfig();
			ftp = new Ftp(config.getHost(), config.getPort(), config
					.getUsername(), config.getPassword());
			ftp.login();
		} catch (IOException e1) {
			e1.printStackTrace();
			return false;
		}
		InputStream is = null;
		try {
			is = ftp.getInputStream(path);
			FileUtils.copyStream(is, out);
			//CipherUtils.decipher(is, out);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if (is != null) {
				FileUtils.closeStream(is);
			}
			ftp.logout();
		}
		return true;
	}

}

